# coding: gb2312
# Copyright (C), 2013-2060, NetEase.
# Author: lixin
# Date: 2013-5-17
# Description: 
import subject_module

class WeatherData(subject_module.Subject):  
    def __init__(self):  
        self.observers = []  
    
    def register(self, observer):  
        if observer not in self.observers:  
            self.observers.append(observer)  
    
    def deregister(self, observer):  
        if observer in self.observers:  
            self.observers.remove(observer)  
  
    def notify_observers(self):  
        for o in self.observers:  
            o.update(self.temperature, self.humidity, self.pressure)  
  
    def data_changed(self):  
        self.notify_observers()  
  
    def set_data(self, temperature, humidity, pressure):  
        self.temperature = temperature  
        self.humidity = humidity  
        self.pressure = pressure  
        self.data_changed()  
  
  
class CurrentDisplay(subject_module.Observer, subject_module.DisplayElement):  
    def __init__(self, weather_data=None):  
        self.weather_data = weather_data  
        self.weather_data.register(self)  
  
    def update(self, temperature, humidity, pressure):  
        self.temperature = temperature   
        self.humidity = humidity  
        self.pressure = pressure  
        self.display()  
  
    def display(self):  
        print "Current Data: temperature=%s, humidity=%s, pressure=%s"%(self.temperature, self.humidity, self.pressure)  
  
class AverageDisplay(subject_module.Observer, subject_module.DisplayElement):  
    def __init__(self, weather_data=None):  
        self.temperature = []  
        self.humidity = []  
        self.pressure = []  
        self.weather_data = weather_data  
        self.weather_data.register(self)  
  
    def update(self, temperature, humidity, pressure):  
        self.temperature.append(temperature)  
        self.humidity.append(humidity)  
        self.pressure.append(pressure)  
        self.display()  
  
    def average(self,lst):  
        n = 0
        for x in lst:  
            n += x  
        return n/len(lst)  
  
    def display(self):  
        print "Average Data: temperature=%s, humidity=%s, pressure=%s"%(self.average(self.temperature), self.average(self.humidity), self.average(self.pressure))
        
        

if __name__ == '__main__':  
    weather_data = WeatherData()  
    
    current = CurrentDisplay(weather_data)  
    average = AverageDisplay(weather_data)  
    
    weather_data.set_data(18,70,100); print  
    weather_data.set_data(20,80,120); print  
    weather_data.set_data(22,90,80); print  
    weather_data.set_data(24,100,40); print  
    
    weather_data.deregister(average)  
    weather_data.set_data(30,70,100); print  
    weather_data.set_data(40,70,120); print   
    
    "test222222"        